<template>
  <XenPageLayout
    title="测试页面"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <view class="form-card">
        <view class="card-header">
          <text class="card-title">物料选择测试</text>
          <text class="card-subtitle">请选择物料型号</text>
        </view>

        <view class="card-content">
          <view class="form-field">
            <view class="field-label">
              <text class="label-text">选择物料（全部）</text>
              <text class="required-mark">*</text>
            </view>
            <XenMaterialPicker
              v-model="formData.materialName"
              placeholder="请选择物料型号"
              :isKeyAttribute="false"
              @change="handleMaterialChange"
            />
            <view v-if="formErrors.materialName" class="field-error">
              {{ formErrors.materialName }}
            </view>
          </view>

          <view class="form-field">
            <view class="field-label">
              <text class="label-text">选择物料（仅关键属性）</text>
              <text class="required-mark">*</text>
            </view>
            <XenMaterialPicker
              v-model="formData.keyMaterialName"
              placeholder="请选择关键物料型号"
              :isKeyAttribute="true"
              @change="handleKeyMaterialChange"
            />
            <view v-if="formErrors.keyMaterialName" class="field-error">
              {{ formErrors.keyMaterialName }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { computed } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenMaterialPicker from "@/components/XenMaterialPicker/XenMaterialPicker.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import { useTestInfo } from "./composables/useInfo";
import type { ISysMaterial } from "@/components/XenMaterialPicker/type/interface";

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "cancel",
    label: "取消",
    type: "default" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用测试单据信息 Composable
const { formData, formErrors, validateField, submitForm } = useTestInfo();

// 物料选择变化处理
const handleMaterialChange = (
  value: string,
  material: ISysMaterial | null,
  model: string,
) => {
  console.log("选中的物料型号（全部）:", model);
  console.log("选中的物料信息（全部）:", material);
  // 清除错误提示
  formErrors.value.materialName = "";
};

// 关键属性物料选择变化处理
const handleKeyMaterialChange = (
  value: string,
  material: ISysMaterial | null,
  model: string,
) => {
  console.log("选中的物料型号（关键属性）:", model);
  console.log("选中的物料信息（关键属性）:", material);
  // 清除错误提示
  formErrors.value.keyMaterialName = "";
};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "cancel":
      handleCancel();
      break;
    case "submit":
      handleSubmit();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 取消按钮
const handleCancel = () => {
  uni.navigateBack();
};

// 提交表单
const handleSubmit = async () => {
  uni.showLoading({ title: "提交中..." });

  // 使用Composable中的提交方法
  const response = await submitForm();

  uni.hideLoading();

  if (response.success) {
    uni.showToast({
      title: "提交成功",
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
    });
  } else {
    // 处理不同类型的错误信息
    let errorMessage = "提交失败，请重试";

    if (response.error) {
      // 显示具体的业务错误信息
      errorMessage = response.error;
    } else if (response.validation?.firstErrorMessage) {
      // 显示表单验证错误信息
      errorMessage = response.validation.firstErrorMessage;
    }

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000, // 延长显示时间，让用户能看清错误信息
    });
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  min-height: 75vh;
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  // 为固定底部按钮预留空间：按钮44px + 上下padding32px + 边框1px + 缓冲15px + 安全区域
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));

  .form-card {
    background-color: #ffffff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

    .card-header {
      padding: 20px;
      background: linear-gradient(
        135deg,
        rgba(102, 126, 234, 0.1) 0%,
        rgba(118, 75, 162, 0.1) 100%
      );
      border-bottom: 1px solid #f0f0f0;

      .card-title {
        display: block;
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }

      .card-subtitle {
        display: block;
        font-size: 13px;
        color: #666;
      }
    }

    .card-content {
      padding: 20px;

      .form-field {
        .field-label {
          display: flex;
          align-items: center;
          margin-bottom: 12px;

          .label-text {
            font-size: 14px;
            font-weight: 500;
            color: #333;
          }

          .required-mark {
            margin-left: 4px;
            color: #ff4d4f;
            font-size: 14px;
          }
        }

        .field-error {
          margin-top: 8px;
          font-size: 12px;
          color: #ff4d4f;
        }
      }
    }
  }
}
</style>
